<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />














  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="netty," />








  <link rel="shortcut icon" type="image/x-icon" href="/images/favicon.ico?v=5.1.2" />






<meta name="keywords" content="netty">
<meta property="og:type" content="article">
<meta property="og:title" content="从Netty3升级到Netty4实战">
<meta property="og:url" content="http://hunfan.top/2018/10/12/从Netty3升级到Netty4实战/index.html">
<meta property="og:site_name" content="混饭&#39;s Notes">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://hunfan.top/upload/homePage/20181017164401.jpg">
<meta property="og:image" content="http://hunfan.top/upload/Netty3升级Netty4/Netty3升级Netty4_1.png">
<meta property="og:image" content="http://hunfan.top/upload/Netty3升级Netty4/Netty3升级Netty4_2.png">
<meta property="og:image" content="http://hunfan.top/upload/Netty3升级Netty4/Netty3升级Netty4_3.png">
<meta property="og:updated_time" content="2019-01-10T02:53:53.380Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="从Netty3升级到Netty4实战">
<meta name="twitter:image" content="http://hunfan.top/upload/homePage/20181017164401.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '77ZW8HG1F0',
      apiKey: '924aaf9b16831d3af864330abb1b94cf',
      indexName: 'github',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键词进行搜索","hits_empty":"找不到关于” ${query} ”的文章","hits_stats":"共找到 ${hits} 篇文章，花了 ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://hunfan.top/2018/10/12/从Netty3升级到Netty4实战/"/>



<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
</script>



	<meta name="google-site-verification" content="7cmTqceXKE0HPzXSCTPWvChlMw-OZuC3GLENr9qj9XM" />


  <title>从Netty3升级到Netty4实战 | 混饭's Notes</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
	<a target="_blank" href="https://github.com/hf-hf" class="github-corner" aria-label="Fork me on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
	
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">混饭's Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Quick notes</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  
  <div class="algolia-popup popup search-popup">
    <div class="algolia-search">
      <div class="algolia-search-input-icon">
        <i class="fa fa-search"></i>
      </div>
      <div class="algolia-search-input" id="algolia-search-input"></div>
    </div>

    <div class="algolia-results">
      <div id="algolia-stats"></div>
      <div id="algolia-hits"></div>
      <div id="algolia-pagination" class="algolia-pagination"></div>
    </div>

    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
  </div>




    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://hunfan.top/2018/10/12/从Netty3升级到Netty4实战/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="混饭">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="混饭's Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">从Netty3升级到Netty4实战</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-10-12T18:11:32+08:00">
                2018-10-12
              </time>
            

            

            
          </span>

          

          
            
          

          
          
             <span id="/2018/10/12/从Netty3升级到Netty4实战/" class="leancloud_visitors" data-flag-title="从Netty3升级到Netty4实战">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="/upload/homePage/20181017164401.jpg" alt="homePage"><br><a id="more"></a></p>
<h2 id="情景"><a href="#情景" class="headerlink" title="情景"></a>情景</h2><p>原来有一版程序，使用的Netty版本是3.7.0Final，最近正好要修改，就顺带把Netty版本升级一下，目标版本4.0.36.Final。</p>
<h2 id="依赖"><a href="#依赖" class="headerlink" title="依赖"></a>依赖</h2><p>因为历史原因（作者从jboss跑路）、Channel状态模型变化等因素影响，Netty4并不能向下兼容Netty3，因此升级需要修改不兼容的代码。</p>
<p>首先变更的就是依赖关系，调查发现，Netty团队大概从3.3.0开始，将dependency groupId由org.jboss.netty改为了io.netty。</p>
<p>由于之前所使用版本是3.7.0Final，在3.3.0之后Maven这里不需要修改，但是代码内部引用的接口、类，在3.7.0Final版本仍为org.jboss.netty，也就说虽然依赖在3.3.0就已经从org.jboss.netty迁到了io.netty，但是内部代码的包结构到3.7.0Final还是原来的org.jboss.netty，如下图。</p>
<p><img src="/upload/Netty3升级Netty4/Netty3升级Netty4_1.png" alt="Netty3升级Netty4_1.png"></p>
<p>因此升级4.0.36.Final，所有原来引用Netty的部分代码，引用包结构都需要修改为io.netty。</p>
<h2 id="Channel状态模型"><a href="#Channel状态模型" class="headerlink" title="Channel状态模型"></a>Channel状态模型</h2><p>这里借用网上的两张图，第一幅图是Netty3的Channel状态模型，第二幅图是Netty4优化之后的模型，可以看到channelOpen，channelBound和channelConnected都已经被channelActive替代。channelDisconnected，channelUnbound和channelClosed也被channelInactive替代。</p>
<p>Netty3 Channel状态模型：</p>
<p><img src="/upload/Netty3升级Netty4/Netty3升级Netty4_2.png" alt="Netty3升级Netty4_2.png"></p>
<p>Netty4 Channel状态模型：</p>
<p><img src="/upload/Netty3升级Netty4/Netty3升级Netty4_3.png" alt="Netty3升级Netty4_3.png"></p>
<p>因此原先Netty3代码使用的部分类，已经被移除，但是会有其他的替代方案。</p>
<h2 id="连接建立"><a href="#连接建立" class="headerlink" title="连接建立"></a>连接建立</h2><p>Netty3代码：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">ServerBootstrap bootstrap = new ServerBootstrap(</span><br><span class="line">        new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),executorService));</span><br><span class="line">  bootstrap.setOption(&quot;RCVBUF_ALLOCATOR&quot;,</span><br><span class="line">          new AdaptiveRecvByteBufAllocator(64, 2000, 65536));</span><br><span class="line">  bootstrap.setOption(ChannelOption.RCVBUF_ALLOCATOR,</span><br><span class="line">          new AdaptiveRecvByteBufAllocator(64, 1024, 65536));</span><br><span class="line">// 设置一个处理客户端消息和各种消息事件的类(Handler)</span><br><span class="line">bootstrap.setPipelineFactory(new ChannelPipelineFactory() &#123;</span><br><span class="line">    @Override</span><br><span class="line">    public ChannelPipeline getPipeline() throws Exception &#123;</span><br><span class="line">        return Channels.pipeline(new ConnectServerHandler(),</span><br><span class="line">                new IdleStateHandler(timer,180,0,0),</span><br><span class="line">                new HeartBeatServerHandler(deviceManager),</span><br><span class="line">                new ReciveMessageChannelHandler(deviceManager, kafkaTemplate));</span><br><span class="line">&#125;&#125;);</span><br><span class="line">bootstrap.bind(new InetSocketAddress(port));</span><br></pre></td></tr></table></figure></p>
<p>Netty4代码：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">EventLoopGroup parentGroup = new NioEventLoopGroup(parentThreadGroupSize);</span><br><span class="line">EventLoopGroup childGroup = new NioEventLoopGroup(childThreadGroupSize);</span><br><span class="line"></span><br><span class="line">try &#123;</span><br><span class="line">    ServerBootstrap b = new ServerBootstrap();</span><br><span class="line">    b.group(parentGroup, childGroup)</span><br><span class="line">            .channel(NioServerSocketChannel.class)</span><br><span class="line">            .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(2048))</span><br><span class="line">            .childOption(ChannelOption.RCVBUF_ALLOCATOR,</span><br><span class="line">                    new AdaptiveRecvByteBufAllocator(64, 2048, 65536))</span><br><span class="line">            .childHandler(new ChannelInitializer&lt;SocketChannel&gt;() &#123;</span><br><span class="line">                @Override</span><br><span class="line">                public void initChannel(SocketChannel ch) throws Exception &#123;</span><br><span class="line">                    ch.pipeline().addLast(new ConnectServerHandler(),</span><br><span class="line">                            new HeartBeatServerHandler(180, 0, 0),</span><br><span class="line">                            new LengthFieldBasedFrameDecoder(1024 * 1024 * 1024, 1, 2,0,0),</span><br><span class="line">                            new ReceiveMessageChannelHandler(deviceManager, kafkaTemplate));</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line"></span><br><span class="line">    // Wait until the server socket is closed.</span><br><span class="line">    ChannelFuture f = b.bind(port).sync();</span><br><span class="line">&#125; catch (InterruptedException e) &#123;</span><br><span class="line">    logger.error(&quot;启动netty异常！&quot;, e);</span><br><span class="line">&#125; finally &#123;</span><br><span class="line">    // Shut down all event loops to terminate all threads.</span><br><span class="line">    parentGroup.shutdownGracefully();</span><br><span class="line">    childGroup.shutdownGracefully();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="心跳"><a href="#心跳" class="headerlink" title="心跳"></a>心跳</h2><p>Netty3时，实现服务器端实现设备心跳使用的是IdleStateAwareChannelHandler，由于之前描述的模型变更影响，这个类现在已经被移除了，但是IdleStateHandler还在，在Netty4中使用IdleStateHandler替换IdleStateAwareChannelHandler实现心跳机制。</p>
<p>Netty3代码：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;</span><br><span class="line"></span><br><span class="line">public class HeartBeatServerHandler extends IdleStateAwareChannelHandler &#123;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e)</span><br><span class="line">            throws Exception &#123;</span><br><span class="line">        log.info(&quot;channelIdle &#123;&#125;&quot;, e.getChannel());</span><br><span class="line">        super.channelIdle(ctx, e);</span><br><span class="line">        Channel channel = e.getChannel();</span><br><span class="line">        //...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Netty4代码：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">import io.netty.handler.timeout.IdleStateHandler;</span><br><span class="line"></span><br><span class="line">public class HeartBeatServerHandler extends IdleStateHandler &#123;</span><br><span class="line"></span><br><span class="line">  public class HeartBeatServerHandler extends IdleStateHandler &#123;</span><br><span class="line">    public HeartBeatServerHandler(int readerIdleTimeSeconds, </span><br><span class="line">                                  int writerIdleTimeSeconds, int allIdleTimeSeconds) &#123;</span><br><span class="line">      super(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在心跳之后的Handler中捕获心跳事件：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception &#123;</span><br><span class="line">    if (evt instanceof IdleStateEvent) &#123;</span><br><span class="line">        IdleStateEvent event = (IdleStateEvent) evt;</span><br><span class="line">        if (event.state() == IdleState.READER_IDLE) &#123;</span><br><span class="line">            //读超时</span><br><span class="line">            logger.info(&quot;READER_IDLE 读超时&quot;);</span><br><span class="line">            Channel channel = ctx.channel();</span><br><span class="line">            logger.info(&quot;channelIdle &#123;&#125;&quot;, ctx.channel());</span><br><span class="line">            if (channel.remoteAddress() != null) &#123;</span><br><span class="line">                String address = channel.remoteAddress().toString();</span><br><span class="line">                Device device = deviceManager.getDeviceByAddress(address);</span><br><span class="line">                if (null != device) &#123;</span><br><span class="line">                    logger.info(&quot;Idle &#123;&#125;-&#123;&#125;&quot;, device, channel);</span><br><span class="line">                &#125; else &#123;</span><br><span class="line">                    channel.close();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; else &#123;</span><br><span class="line">                logger.info(&quot;Idle udp null-&#123;&#125;&quot;, channel);</span><br><span class="line">            &#125;</span><br><span class="line">            ctx.disconnect();</span><br><span class="line">        &#125; else if (event.state() == IdleState.WRITER_IDLE) &#123;</span><br><span class="line">            //写超时</span><br><span class="line">            logger.info(&quot;WRITER_IDLE 写超时&quot;);</span><br><span class="line">        &#125; else if (event.state() == IdleState.ALL_IDLE) &#123;</span><br><span class="line">            //总超时</span><br><span class="line">            logger.info(&quot;ALL_IDLE 总超时&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    ctx.fireUserEventTriggered(evt);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这里Netty4与Netty3获取channel以及remoteAddress的方式也有了变化，在Netty4中这两者都可以从ChannelHandlerContext上下文直接获取了，不再需要Netty3的MessageEvent。</p>
<h2 id="消息处理"><a href="#消息处理" class="headerlink" title="消息处理"></a>消息处理</h2><p>对于消息处理这方面，原来Netty3中我使用的是SimpleChannelUpstreamHandler，Netty4中使用ChannelDuplexHandler替换。</p>
<p>Netty3代码：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">public class ReciveMessageChannelHandler extends SimpleChannelUpstreamHandler &#123;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void finalize() throws Throwable &#123;</span><br><span class="line">        super.finalize();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    @Override</span><br><span class="line">    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception &#123;</span><br><span class="line">        if (e.getMessage() instanceof ChannelBuffer) &#123;</span><br><span class="line">            ChannelBuffer cb = ((ChannelBuffer) e.getMessage());</span><br><span class="line">            //消息处理...</span><br><span class="line">        &#125;</span><br><span class="line">        super.messageReceived(ctx, e);</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e)</span><br><span class="line">              throws Exception &#123;</span><br><span class="line">         super.channelDisconnected(ctx, e);</span><br><span class="line">          logger.info(&quot;**************************^_^^_^^_^**************************&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    @Override</span><br><span class="line">    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) &#123;</span><br><span class="line">      e.getChannel().close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Netty4代码：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line">public class ReceiveMessageChannelHandler extends ChannelDuplexHandler &#123;</span><br><span class="line"></span><br><span class="line">    private static Logger logger = LoggerFactory.getLogger(ReceiveMessageChannelHandler.class);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 用来生成key</span><br><span class="line">     */</span><br><span class="line">    private static final String KAFKA_KEY = &quot;test&quot;;</span><br><span class="line"></span><br><span class="line">    private static final String IF_PARTITION = &quot;0&quot;;</span><br><span class="line"></span><br><span class="line">    private static final Integer PARTITION_NUM = 1;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 默认topic名称</span><br><span class="line">     */</span><br><span class="line">    private static final String DEFAULT_TOPIC_NAME = &quot;nettytest&quot;;</span><br><span class="line"></span><br><span class="line">    private KafkaProducerServer kafkaProducer;</span><br><span class="line"></span><br><span class="line">    private DeviceManager deviceManager;</span><br><span class="line"></span><br><span class="line">    public DeviceManager getDM() &#123;</span><br><span class="line">        return deviceManager;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public ReceiveMessageChannelHandler(DeviceManager deviceManager,</span><br><span class="line">                                        KafkaTemplate&lt;String, String&gt; kafkaTemplate) &#123;</span><br><span class="line">        this.deviceManager = deviceManager;</span><br><span class="line">        this.kafkaProducer = new KafkaProducerServer(kafkaTemplate);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public ReceiveMessageChannelHandler(DeviceManager deviceManager) &#123;</span><br><span class="line">        this.deviceManager = deviceManager;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception &#123;</span><br><span class="line">        ByteBuf buffer = ((ByteBuf) msg);</span><br><span class="line">        //消息处理...</span><br><span class="line">        super.channelRead(ctx, msg);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void disconnect(ChannelHandlerContext ctx, ChannelPromise future) throws Exception &#123;</span><br><span class="line">        super.disconnect(ctx, future);</span><br><span class="line">        logger.info(&quot;*****************disconnect*********^_^^_^^_^**************************&quot;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void close(ChannelHandlerContext ctx, ChannelPromise future) throws Exception &#123;</span><br><span class="line">        super.close(ctx, future);</span><br><span class="line">        logger.info(&quot;*****************close*********^_^^_^^_^**************************&quot;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="消息发送"><a href="#消息发送" class="headerlink" title="消息发送"></a>消息发送</h2><p>消息读取方面，原来Netty3的ChannelBuffer已经由ByteBuf，并且Netty4还专门将其拆分出一个单独的包，其意义在于即使你不用Netty也可以方便的使用ByteBuf处理字节数据。</p>
<p>消息发送方面，Netty3中通过ctx.getChannel().write(ChannelBuffers.wrappedBuffer(replyMsg), e.getRemoteAddress())进行消息发送，需要指定remoteAddress，在Netty4中改变为了ctx.channel().writeAndFlush(Unpooled.buffer().writeBytes(replyMsg))，将数据写入缓冲区并刷新缓冲区，而且也不需要指定需要指定remoteAddress。</p>
<h2 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h2><p>这次对Netty3升级Netty4的过程进行了简单的记录，相同功能在Netty3和Netty4下的实现代码都进行了罗列比对，如果你也恰好遇到相同的问题，希望能对你有所帮助。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/netty/" rel="tag"># netty</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/09/29/Java根据圆心经纬度、半径获取圆的点集/" rel="next" title="Java根据圆心经纬度、半径获取圆的点集">
                <i class="fa fa-chevron-left"></i> Java根据圆心经纬度、半径获取圆的点集
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/10/12/关于SXSSFWorkbook默认行数限制/" rel="prev" title="关于SXSSFWorkbook默认行数限制">
                关于SXSSFWorkbook默认行数限制 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- Go to www.addthis.com/dashboard to customize your tools -->
<div class="addthis_inline_share_toolbox">
  <script type = "text/javascript" src = "//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5b4c0089687a63d1" async = "async" ></script>
</div>

      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zMzEyNC85Njgz"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.png"
               alt="混饭" />
          <p class="site-author-name" itemprop="name">混饭</p>
           
              <p class="site-description motion-element" itemprop="description">重度拖延症患者(-__-)b</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
            
              <a href="/archives/">
            
                <span class="site-state-item-count">52</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">45</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/hf-hf" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                    
                      GitHub
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://gitee.com/hf-hf" target="_blank" title="Gitee">
                  
                    <i class="fa fa-fw fa-gitee"></i>
                  
                    
                      Gitee
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#情景"><span class="nav-number">1.</span> <span class="nav-text">情景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#依赖"><span class="nav-number">2.</span> <span class="nav-text">依赖</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Channel状态模型"><span class="nav-number">3.</span> <span class="nav-text">Channel状态模型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#连接建立"><span class="nav-number">4.</span> <span class="nav-text">连接建立</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#心跳"><span class="nav-number">5.</span> <span class="nav-text">心跳</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#消息处理"><span class="nav-number">6.</span> <span class="nav-text">消息处理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#消息发送"><span class="nav-number">7.</span> <span class="nav-text">消息发送</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#结语"><span class="nav-number">8.</span> <span class="nav-text">结语</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">混饭</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" href="https://coding.net/pages">Hosted by CODING Pages</a> 强力驱动</div>



        
<div class="busuanzi-count">
  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazyload/1.9.3/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>


  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>





  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  








  




  
  
  
    
  
  <link rel="stylesheet" href="//cdn.bootcss.com/instantsearch.js/1.5.0/instantsearch.min.css">

  
  
    
  
  <script src="//cdn.bootcss.com/instantsearch.js/1.5.0/instantsearch.min.js"></script>
  

  <script src="/js/src/algolia-search.js?v=5.1.2"></script>



  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("FbdjjSByqhjHC2t0f5DiTzXi-gzGzoHsz", "EhyT8E3CKzF9CQcem5hx7ftx");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>
